package cn.ly.jvm.loader.diffloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ClassLoader1 extends ClassLoader{
	
	private String rootDir;
	
	public ClassLoader1(String path){
		this.rootDir = path;
	}
	
	public Class<?> loadClass(String className) throws ClassNotFoundException{
		Class clz = findClass(className);
		if(clz != null){
			return clz;
		}
		return super.loadClass(className);
	}
	
	protected Class<?> findClass(String className) throws ClassNotFoundException {
		Class clz = super.findLoadedClass(className);
		if(clz == null){
			byte[] classData = getClassData(className);
			if(classData != null){
				return super.defineClass(className, classData, 0, classData.length);
			}
		}
		return clz;
	}
	
	protected Class<?> getClass(String className){
		return super.findLoadedClass(className);
	}
	
	private byte[] getClassData(String className){
        String path = classNameToPath(className); 
        try { 
            InputStream ins = new FileInputStream(path); 
            ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
            int bufferSize = 4096; 
            byte[] buffer = new byte[bufferSize]; 
            int bytesNumRead = 0; 
            while ((bytesNumRead = ins.read(buffer)) != -1) { 
                baos.write(buffer, 0, bytesNumRead); 
            } 
            return baos.toByteArray(); 
        } catch (IOException e) { 
        } 
        return null; 
	}
	
	private String classNameToPath(String className){
        return rootDir + File.separatorChar 
                + className.replace('.', File.separatorChar) + ".class"; 
	}

}
